package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.utils.FormatUtils;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.rpc.api.TransportCompanyRpcService;
import com.hunttown.mes.rpc.domain.TransportCompanyDTO;
import com.hunttown.mes.rpc.domain.query.TransportCompanyDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * created by wangjunfu on 2019-05-19 01:51:45
 */
@Service
public class TransportCompanyManageService {

    private final static Logger logger = LoggerFactory.getLogger(TransportCompanyManageService.class);

    private final TransportCompanyRpcService rpcService;
    private final Cache jedisCache;

    @Autowired
    public TransportCompanyManageService(TransportCompanyRpcService rpcService, Cache jedisCache) {
        this.rpcService = rpcService;
        this.jedisCache = jedisCache;
    }

    // 新增
    public TransportCompanyDTO insert(TransportCompanyDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(TransportCompanyDTO objDTO) {
        Boolean isNext = rpcService.updateInfoById(objDTO);
        if (isNext) {
            // 刷新缓存
            refreshCacheById(objDTO.getId());
        }
        return isNext;
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(TransportCompanyDTOQuery objDTOQuery) {
        Boolean isNext = rpcService.updateInfoByQuery(objDTOQuery);

        //单体刷新
        if (isNext && objDTOQuery.getW_id() != null) {
            refreshCacheById(objDTOQuery.getW_id());
        }

        //批量刷新缓存
        if (isNext && objDTOQuery.getIds() != null) {
            List<Integer> list = new ArrayList<>();
            try {
                list = (List<Integer>) objDTOQuery.getIds();
            } catch (Exception e) {
                e.printStackTrace();
            }
            refreshCacheByIdList(list);
        }
        return isNext;
    }

    // 通过ID删除
    public Boolean delete(Integer id) {
        Boolean isNext = rpcService.deleteById(id);
        if (isNext) {
            // 刷新缓存
            refreshCacheById(id);
        }
        return isNext;
    }

    // 批量删除
    public Boolean deleteForBatch(String clearIds) {

        //处理 “,5,6,7,” 为List
        List<Integer> idList = FormatUtils.commaToList_Integer(clearIds);

        if (idList.size() == 0) {
            return false;
        }

        TransportCompanyDTOQuery query = new TransportCompanyDTOQuery();
        query.setDeleteFlag(1);
        query.setIds(idList);

        Boolean isNext = rpcService.updateInfoByQuery(query);
        if (isNext) {
            // 刷新缓存
            refreshCacheByIdList(idList);
        }

        return isNext;
    }

    // 通过ID获取
    public TransportCompanyDTO getById(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    /**
     * 从缓存中获取公司名称
     * 如果不存在，再从数据库中获取
     *
     * @param id 公司id
     * @return 公司名称
     */
    public String getCompanyName(Integer id) {
        TransportCompanyDTO companyDTO = getFromCacheId(id);
        return companyDTO == null ? "--" : companyDTO.getCompanyNameCn();
    }

    //根据英文名称获取数据
    public TransportCompanyDTO getByCompanyName(String companyName) {
        TransportCompanyDTOQuery query = new TransportCompanyDTOQuery();
        query.setCompanyName(companyName);
        query.setStopFlag(0);
        return getByQuery(query);
    }

    public TransportCompanyDTO getByCompanyNameCn(String companyNameCn) {
        TransportCompanyDTOQuery query = new TransportCompanyDTOQuery();
        query.setCompanyNameCn(companyNameCn);
        query.setStopFlag(0);
        return getByQuery(query);
    }

    //获取自营单位ID
    public List<Integer> getSelfCompany() {
        TransportCompanyDTOQuery query = new TransportCompanyDTOQuery();
        query.setIsSelf(1);
        query.setStopFlag(0);
        Page<TransportCompanyDTO> dataPage = getForPage(query);

        List<Integer> ids = new ArrayList<>();
        for (TransportCompanyDTO item : dataPage.getItems()) {
            ids.add(item.getId());
        }
        return ids;
    }

    // 通过Query获取
    public TransportCompanyDTO getByQuery(TransportCompanyDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<TransportCompanyDTO> getForPage(TransportCompanyDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    // 改变某条记录的使用状态
    public Boolean changeState(Integer id, Integer state) {
        TransportCompanyDTO obj = new TransportCompanyDTO();
        obj.setStopFlag(state);
        obj.setId(id);
        return updateInfoById(obj);
    }

    /**
     * 先从缓存中获取数据
     * 如果缓存为空，从数据库中获取，并将获取的数据添加到缓存。
     *
     * @param id id
     * @return
     */
    public TransportCompanyDTO getFromCacheId(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }

        TransportCompanyDTO obj = jedisCache.oget(KeyConstants.COMPANY_INFO_KEY_ID + id, TransportCompanyDTO.class);
        if (obj == null) {
            obj = getById(id);
            if (obj != null) {
                jedisCache.oset(KeyConstants.COMPANY_INFO_KEY_ID + id, obj);
            }
        }

        return obj;
    }

    //region 刷新缓存

    /**
     * 刷公司缓存
     *
     * @param id 公司id
     */
    public void refreshCacheById(Integer id) {
        if (id == null || id <= 0) {
            return;
        }

        TransportCompanyDTO obj = getById(id);
        if (obj != null) {
            jedisCache.delete(KeyConstants.COMPANY_INFO_KEY_ID + id);
        }
    }

    /**
     * 刷公司缓存(批量)
     *
     * @param idList
     */
    public void refreshCacheByIdList(List<Integer> idList) {
        if (idList == null || idList.size() == 0) {
            return;
        }

        for (Integer id : idList) {
            refreshCacheById(Integer.valueOf(id.toString()));
        }
    }
    //endregion

    //region 整理数据

    /**
     * 取出每条记录的子类，一并返回
     *
     * @param list
     * @return
     */
    public List<TransportCompanyDTO> getChildrenForEach(List<TransportCompanyDTO> list, String mark) {
        if (list == null || list.size() == 0) {
            return list;
        }

        List<TransportCompanyDTO> return_list = new ArrayList<>();
        List<TransportCompanyDTO> child_list = new ArrayList<>();

        for (TransportCompanyDTO item : list) {
            child_list = getChildrenById(item, mark);
            return_list.addAll(child_list);
        }

        return return_list;
    }

    /**
     * 取出每条记录的子类，一并返回（具体实施）
     *
     * @param dto
     * @return
     */
    public List<TransportCompanyDTO> getChildrenById(TransportCompanyDTO dto, String mark) {
        List<TransportCompanyDTO> child_list = new ArrayList<>();
        child_list.add(dto);

        if (mark.equals("|")) {
            mark += "┄";
        } else {
            mark += " ┄";
        }

        TransportCompanyDTOQuery query = new TransportCompanyDTOQuery();
        query.setParentId(dto.getId());
        query.setStopFlag(0);
        query.setPageSize(1000);
        Page<TransportCompanyDTO> dataPage = getForPage(query);

        if (dataPage != null && dataPage.getItems().size() > 0) {
            for (TransportCompanyDTO item : dataPage.getItems()) {
                item.setCompanyNameCn(mark + " " + item.getCompanyNameCn());
                List<TransportCompanyDTO> next_list = getChildrenById(item, mark);
                child_list.addAll(next_list);
            }
        }

        return child_list;
    }

    /**
     * 通过递归得到树形结构
     *
     * @param list
     * @param parentId
     * @param splitMark
     * @return
     */
    public List<TransportCompanyDTO> getListByRecursion(List<TransportCompanyDTO> list, Integer parentId, String splitMark) {
        List<TransportCompanyDTO> returnList = new ArrayList<>();

        if (parentId > 0) {
            if (splitMark.equals("|")) {
                splitMark += "┄";
            } else {
                splitMark += " ┄";
            }
        }

        if (list != null && list.size() > 0) {
            List<TransportCompanyDTO> mainList = list.stream().filter(s -> s.getParentId().equals(parentId)).collect(Collectors.toList());

            for (TransportCompanyDTO item : mainList) {
                if (parentId > 0) {
                    item.setCompanyNameCn(String.format("%s %s", splitMark, item.getCompanyNameCn()));
                }
                returnList.add(item);

                List<TransportCompanyDTO> next_list = getListByRecursion(list, item.getId(), splitMark);
                for (TransportCompanyDTO item_child : next_list) {
                    returnList.add(item_child);
                }
            }
        }

        return returnList;
    }
    //endregion

    //region 模糊搜索公司
    public List<Map<String, String>> getSimilarCompany(String similar, Integer companyType) {
        return rpcService.selectSimilarCompany(similar, companyType);
    }
    //endregion
}